import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import 'z_container.dart';

final _map = <String, Image>{};

class ZImage extends StatelessWidget {
  final String? asset;
  final double? width;
  final double? height;
  final BoxFit? fit;
  final Uint8List? bytes;
  final int mode;
  final double? radius;
  final String? url;

  const ZImage({super.key, required this.asset, this.height, this.fit, this.width, this.radius})
      : bytes = null,
        url = null,
        mode = 0;

  const ZImage.memory({super.key, this.height, this.fit, this.width, this.bytes, this.radius})
      : asset = null,
        url = null,
        mode = 1;

  const ZImage.network({super.key, this.height, this.fit, this.width, this.radius, this.url})
      : asset = null,
        bytes = null,
        mode = 2;

  @override
  Widget build(BuildContext context) {
    Widget child;
    if (mode == 1) {
      if (bytes != null) {
        // child = ExtendedImage.memory(
        //   bytes!,
        //   width: width?.r,
        //   height: height?.r,
        //   fit: fit,
        //   key: ValueKey(String.fromCharCodes(bytes!)),
        // );
        child = _map['$width-$height-${String.fromCharCodes(bytes!)}'] ??=
            Image.memory(bytes!, width: width?.r, height: height?.r, fit: fit, key: ValueKey(String.fromCharCodes(bytes!)));
      } else {
        child = _empty;
      }
    } else {
      child = Image.asset(asset!, width: width?.r, height: height?.r, fit: fit);
    }
    if (radius != null) {
      return ClipRRect(
        borderRadius: BorderRadius.circular(radius!.r),
        child: child,
      );
    } else {
      return child;
    }
  }

  Widget get _empty => ZContainer(width: width, height: height, child: const Icon(Icons.error_outline));
}
